package controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.ejb.Stateless;

import crud.PatientDetailCRUD;

import entities.PatientDetail;

/**
 * Session Bean implementation class PatientDAO
 */
@Stateless
public class PatientDAO implements PatientDAORemote {

	public PatientDAO() {
	}

	public List<PatientDetail> getAllPatient() {
		PatientDetailCRUD crud = new PatientDetailCRUD();
		List<PatientDetail> patients = crud.readAll();
		return patients;
	}

	public String createPatient(String firstName, String lastName, String address,
			String emgContact, Date appointmentDay) {
		PatientDetailCRUD crud = new PatientDetailCRUD();
		return crud.create_Patient_Examine_User(address, emgContact, firstName, lastName,
				appointmentDay);
	}

	public PatientDetail getPatientById(String id) {
		PatientDetailCRUD crud = new PatientDetailCRUD();
		PatientDetail patient = crud.readById(Integer.parseInt(id));
		return patient;
	}

	public List<PatientDetail> getPatientByName(String firstName, String lastName) {
		PatientDetailCRUD crud = new PatientDetailCRUD();
		firstName = firstName.trim().toLowerCase();
		lastName = lastName.trim().toLowerCase();

		String queryString = "";
		List<PatientDetail> patientDetails = new ArrayList<PatientDetail>();

		if (firstName.equals("") && !lastName.equals("")) {
			queryString = "SELECT p FROM PatientDetail p WHERE LOWER (p.lastName) LIKE '%" + lastName
					+ "%'";
		} else if (!firstName.equals("") && lastName.equals("")) {
			queryString = "SELECT p FROM PatientDetail p WHERE LOWER (p.firstName) LIKE '" + firstName
					+ "%'";

		} else if (!firstName.equals("") && !lastName.equals("")) {
			queryString = "SELECT p FROM PatientDetail p WHERE ( (LOWER (p.firstName) LIKE '"
					+ firstName + "%') OR (LOWER (p.firstName) LIKE '%" + lastName + "%'))";
		}

		if (!queryString.equals("")) {
			patientDetails = crud.readByQuery(queryString);
		}

		return patientDetails;
	}

	public String updatePatient(String idPatientDetail, String firstName, String lastName,
			String address, String emgContact) {
		PatientDetailCRUD crud = new PatientDetailCRUD();
		PatientDetail patient = crud.readById(Integer.parseInt(idPatientDetail));
		patient.setAddress(address);
		patient.setEmgContact(emgContact);
		patient.setFirstName(firstName);
		patient.setLastName(lastName);
		return crud.update(patient);
	}

	public String deletePatient(String idPatientDetail) {
		PatientDetailCRUD crud = new PatientDetailCRUD();
		String tem = crud.delete_NoneExamine_Patient(Integer.parseInt(idPatientDetail));
		return tem;
	}

}
